package com.module_live.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.herewhite.sdk.Room;
import com.herewhite.sdk.WhiteBroadView;
import com.herewhite.sdk.domain.AkkoEvent;
import com.herewhite.sdk.domain.AnimationMode;
import com.herewhite.sdk.domain.EventEntry;
import com.herewhite.sdk.domain.EventListener;
import com.herewhite.sdk.domain.ViewMode;
import com.lib.app.ARouterPathUtils;
import com.lib.app.ActivityUtils;
import com.lib.app.CodeUtil;
import com.lib.app.FragmentTag;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.fragment_deal.FragmentCustomUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.utils.status_bar.QMUI.QMUIStatusBarHelper;
import com.lib.fastkit.utils.status_bar.StatusBarUtil;
import com.lib.fastkit.utils.time_deal.TimeUtils;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.dialog.normal.OneButtonDialog;
import com.lib.fastkit.views.dialog.zenhui.AlertDialog;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.observer.ObserverListener;
import com.lib.observer.ObserverManager;
import com.lib.utls.picture_select.PhotoUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.module_live.R;
import com.module_live.bean.CloseRoomBean;
import com.module_live.bean.DaYiConectTimeRecordBean;
import com.module_live.bean.MyTrackInfo;
import com.module_live.bean.RoomChatBean;
import com.module_live.bean.coachstudy.GetUserNameFromPhone;
import com.module_live.bean.coachstudy.StudentLuckyDrawBean;
import com.module_live.fragment.coachstudy.StudentLuckyDrawWebFragment;
import com.module_live.fragment.coachstudy.StudyControlMenuFragment;
import com.module_live.fragment.coachstudy.StudyUserListFragment;
import com.module_live.fragment.coachstudy.StudyWhiteBroadFragment;
import com.module_live.utils.MyHashMap;
import com.module_live.utils.WhiteBoardUtils;
import com.module_live.utils.socket.IMSocketUtils;
import com.qiniu.droid.rtc.QNAudioSourceCallback;
import com.qiniu.droid.rtc.QNBeautySetting;
import com.qiniu.droid.rtc.QNCameraSwitchResultCallback;
import com.qiniu.droid.rtc.QNErrorCode;
import com.qiniu.droid.rtc.QNRTCEngine;
import com.qiniu.droid.rtc.QNRTCEngineEventListener;
import com.qiniu.droid.rtc.QNRTCSetting;
import com.qiniu.droid.rtc.QNRoomState;
import com.qiniu.droid.rtc.QNSourceType;
import com.qiniu.droid.rtc.QNStatisticsReport;
import com.qiniu.droid.rtc.QNSurfaceView;
import com.qiniu.droid.rtc.QNTrackInfo;
import com.qiniu.droid.rtc.QNTrackKind;
import com.qiniu.droid.rtc.QNVideoFormat;
import com.qiniu.droid.rtc.model.QNAudioDevice;

import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.Nullable;

import static com.module_live.utils.config.LiveConfig.DEFAULT_BITRATE;
import static com.module_live.utils.config.LiveConfig.DEFAULT_FPS;
import static com.module_live.utils.config.LiveConfig.DEFAULT_RESOLUTION;


/**
 * 老师辅导学生家庭作业直播间
 */
@Route(path = ARouterPathUtils.Tablet_CoachStudyLivingActivity)
public class CoachStudyLivingActivity extends BaseRoomActivity implements
        QNRTCEngineEventListener, QNAudioSourceCallback, ObserverListener {

    //房间Token
    @Autowired(name = "roomToken")
    String roomToken;
    //当前房间的老师
    @Autowired(name = "teacherPhone")
    public static String teacherPhone;
    //房间名称
    @Autowired(name = "roomName")
    String roomName;
    //当前用户的手机号
    @Autowired(name = "userPhone")
    String userPhone;
    //白板UUID
    @Autowired(name = "uuid")
    String uuid;
    //白板Token
    @Autowired(name = "whitetoken")
    String whitetoken;

    @Autowired(name = "course_id")
    public static String course_id;

    @Autowired(name = "studentId")
    String studentId;

    @Autowired(name = "teacherId")
    String teacherId;

    //身份表示(1老师 0学生)
    private String identity = "";
    private String userIcon = "";
    private String userName = "";
    private String userToken = "";

    //获取直播间创建者学管老师的信息，方便用户列表中操作
//    public static String roomCreatePhone = "";

    //如果老师异常退出直播间
    int classState = 0;

    //Map用于保存进入直播间用户的信息(每进一个用户需要添加一次，反之移除)
    public static MyHashMap<String, MyTrackInfo> trackInfoMap = new MyHashMap<>();

    //直播间老师及学管信息容器
    public static MyHashMap<String, MyTrackInfo> teacherTrackInfoMap = new MyHashMap<>();
    //直播间学生及学管信息容器
    public static MyHashMap<String, MyTrackInfo> studentTrackInfoMap = new MyHashMap<>();

    //直播引擎
    private static QNRTCEngine mEngine;

    //本地的视频流
    private QNTrackInfo localVideoTrack;
    //本地的音频流
    private QNTrackInfo localAudioTrack;

    //正在播放的流(包含视频流和音频流)
    private MyTrackInfo playingTrack;

    //聊天室长连接(公司服务器)用于聊天使用
    public static IMSocketUtils imSocketUtils;

    //用于判断老师是否点击了下课按钮
    private boolean isTeacherClose = false;

    //用于记录直播间时长
    long baseTimer = SystemClock.elapsedRealtime();

    Handler myhandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (0 == baseTimer) {
                baseTimer = SystemClock.elapsedRealtime();
            }

            int time = (int) ((SystemClock.elapsedRealtime() - baseTimer) / 1000);
            String hh = new DecimalFormat("00").format(time / 3600);
            time = time - Integer.parseInt(hh) * 3600;
            String mm = new DecimalFormat("00").format(time / 60);

            String ss = new DecimalFormat("00").format(time % 60);
            if (null != tvTime) {
                tvTime.setText(hh + ":" + mm + ":" + ss);
            }
            Message message = Message.obtain();
            message.what = 0x0;
            sendMessageDelayed(message, 1000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         * 初始换页面配置
         */
        QMUIStatusBarHelper.setStatusBarDarkMode(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        StatusBarUtil.statusBarTintColor(this, getResources().getColor(R.color.transparent));
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_coachstudylive);

        ARouter.getInstance().inject(this);

        ObserverManager.getInstance().add(this);

        initBaseData();

        /**
         * 通过横竖屏来获取不同的控件
         * 横竖屏是两套页面
         */
        findView();

        /**
         * 控制
         */
        initStudyControlFragment();

        /**
         * 白板
         */
        initWhiteBorad();
        initStudyWhiteBroadFragment();


        /**
         * 消息控制
         */
        initChat();

        /**
         * 直播
         */
        initEngine();

        /**
         * 用户列表
         */
        initStudyUserListFragment();

        //设置横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        if (StringUtil.isNotEmpty(identity, true)) {
            //只有学生才可以抽奖
            if ("2".equals(identity)) {
                //显示抽奖网页
                initLuckyView();
            }
        }
    }

    private void initLuckyView() {

        HttpUtils.with(this)
                .addParam("requestType", "FIRST_RAFFLE")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<StudentLuckyDrawBean>() {
                    @Override
                    public void onSuccess(StudentLuckyDrawBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj() != null) {
                                //0-第一次，1-不是第一次
                                LogUtil.e("是否可抽奖的状态值：" + result.getObj().getIs_first());
                                if (0 == result.getObj().getIs_first()) {
                                    if (StringUtil.isNotEmpty(result.getObj().getLucky_address(), true)) {
                                        showNick();
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }


    FrameLayout frControl, frUserList, frWhiteBroad;

    //显示大屏直播画面的View
    private QNSurfaceView localSurfaceView;
    //显示大屏学生画面的View
    private QNSurfaceView studentSurfaceView;

    //老师计时
    private TextView tvTime, tvCamera;


    /**
     * 获取控件ID
     */
    private void findView() {

        frUserList = findViewById(R.id.fr_userlist);
        frControl = findViewById(R.id.fr_control);
        frWhiteBroad = findViewById(R.id.fr_white);

        localSurfaceView = findViewById(R.id.qn_view_teacher);
        studentSurfaceView = findViewById(R.id.qn_view_student);
        tvTime = findViewById(R.id.tv_time);
        tvCamera = findViewById(R.id.tv_camera);

        localSurfaceView.setZOrderOnTop(false);
        localSurfaceView.setZOrderMediaOverlay(false);

        studentSurfaceView.setZOrderOnTop(false);
        studentSurfaceView.setZOrderMediaOverlay(false);

        studentSurfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ("1".equals(identity)) {
                    if (studentSurfaceView.getVisibility() == View.GONE) {
                        studentSurfaceView.setVisibility(View.GONE);
                        frUserList.setVisibility(View.VISIBLE);
                    } else {
                        studentSurfaceView.setVisibility(View.VISIBLE);
                        frUserList.setVisibility(View.GONE);
                    }
                }
            }
        });

        if ("1".equals(identity)) {
            tvCamera.setVisibility(View.VISIBLE);
        } else {
            tvCamera.setVisibility(View.GONE);
        }

        tvCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEngine == null) {
                    mEngine = QNRTCEngine.createEngine(getApplicationContext(), setting, CoachStudyLivingActivity.this);
                }
                mEngine.switchCamera(new QNCameraSwitchResultCallback() {
                    @Override
                    public void onCameraSwitchDone(boolean b) {

                        //true为前置摄像头，false为后置摄像头
                        LogUtil.e("切换摄像头========================>" + b);

                    }

                    @Override
                    public void onCameraSwitchError(String s) {

                        LogUtil.e("切换摄像头失败，原因是：========================>" + s);
                    }
                });

            }
        });

    }

    StudentLuckyDrawWebFragment nickNameFragment;
    AlertDialog dialog;

    private void showNick() {

        dialog = new AlertDialog.Builder(this)
                .setContentView(R.layout.dialog_student_luckydraw)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (nickNameFragment != null) {
                            getSupportFragmentManager().beginTransaction().remove(nickNameFragment).commitAllowingStateLoss();
                            nickNameFragment = null;
                        }
                    }
                })
                .fullWidth()
                .addDefaultAnimation()
                .show();

        nickNameFragment = (StudentLuckyDrawWebFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_lucky);
    }

    /**
     * 初始化聊天
     */
    private void initChat() {

        imSocketUtils = IMSocketUtils.getInstance().start(roomName, userToken);
    }

    @Override
    protected void onResume() {
        super.onResume();

        //发送计时消息
        myhandler.sendMessageDelayed(Message.obtain(myhandler, 1), 1000);
        if ("1".equals(identity)) {
        } else {
            tvTime.setVisibility(View.GONE);
        }
    }

    private void initBaseData() {

        /**
         * 初始化页面数据
         */
        roomToken = getIntent().getStringExtra("roomToken");
        roomName = getIntent().getStringExtra("roomName");
        teacherPhone = getIntent().getStringExtra("teacherPhone");
        userPhone = getIntent().getStringExtra("userPhone");
        whitetoken = getIntent().getStringExtra("whitetoken");
        uuid = getIntent().getStringExtra("uuid");

        course_id = getIntent().getStringExtra("course_id");
        studentId = getIntent().getStringExtra("studentId");
        teacherId = getIntent().getStringExtra("teacherId");

        identity = SharedPreferenceManager.getInstance(this).getUserCache().getUserIdentity();
        userIcon = SharedPreferenceManager.getInstance(this).getUserCache().getUserHeadUrl();
        userName = SharedPreferenceManager.getInstance(this).getUserCache().getUserName();
        userToken = SharedPreferenceManager.getInstance(this).getUserCache().getUserToken();
    }

    //控制页面
    public static StudyControlMenuFragment studyControlFragment;

    //用户列表页面
    public static StudyUserListFragment studyUserListFragment;

    //直播间白板
    public static StudyWhiteBroadFragment studyWhiteBroadFragment;

    private void initStudyControlFragment() {

        studyControlFragment = new StudyControlMenuFragment(roomName);
        studyControlFragment.setStudyControlMenuFragmentListener(controlFragmentListener);
        FragmentCustomUtils.setFragment(this, R.id.fr_control, studyControlFragment, FragmentTag.CoachStudyControlFragment);
    }

    private void initStudyUserListFragment() {

        studyUserListFragment = new StudyUserListFragment();
        studyUserListFragment.setStudyUserListFragmentListener(userListFragmentListener);
        FragmentCustomUtils.setFragment(this, R.id.fr_userlist, studyUserListFragment, FragmentTag.CoachStudyUserListFragment);
    }

    private void initStudyWhiteBroadFragment() {

        studyWhiteBroadFragment = new StudyWhiteBroadFragment(whiteBroadView, whiteBoardRoom);
        FragmentCustomUtils.setFragment(this, R.id.fr_white, studyWhiteBroadFragment, FragmentTag.CoachStudyWhiteBroadFragment);
    }

    /**
     *==============================================================================================
     * ==========================================================================直播相关
     * =============================================================================================
     */

    /**
     * 初始化直播
     */
    private QNRTCSetting setting = new QNRTCSetting();

    private void initEngine() {

        setQuality();

        /**
         * 设置是否默认音频路由为扬声器
         *
         * @param defaultAudioRouteToSpeakerphone 若为 true，则默认为扬声器，若为 false，则为听筒
         *
         */
//        SharedPreferences preferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
//        boolean isLowSampleRateEnabled = preferences.getInt(Config.SAMPLE_RATE, Config.HIGH_SAMPLE_RATE) == Config.LOW_SAMPLE_RATE;
//        setting.setLowAudioSampleRateEnabled(isLowSampleRateEnabled)

        setting.setDefaultAudioRouteToSpeakerphone(true);

        mEngine = QNRTCEngine.createEngine(getApplicationContext(), setting, this);

        initBeauty();

        //视频流
        localVideoTrack = mEngine.createTrackInfoBuilder()
                .setSourceType(QNSourceType.VIDEO_CAMERA)
                .setMaster(true)
                .create();

        //音频流
        localAudioTrack = mEngine.createTrackInfoBuilder()
                .setSourceType(QNSourceType.AUDIO)
                .setBitrate(64 * 1000)// 设置音频码率
                .setMaster(true)
                .create();
        LogUtil.e("当前房间的roomToken为:" + roomToken);

        //因为区分了老师，学生、学管，所有需要根据身份来判断将信息加入哪一个容器中
//
//        MyTrackInfo myTrackInfo = new MyTrackInfo(userPhone, localVideoTrack, null, identity);
//        if ("1".equals(identity)) {
//
//            teacherTrackInfoMap.put(userPhone, myTrackInfo);
//        } else if ("2".equals(identity)) {
//
//            studentTrackInfoMap.put(userPhone, myTrackInfo);
//        }
//        playingTrack = myTrackInfo;

//        MyTrackInfo myTrackInfo = new MyTrackInfo(userPhone, localVideoTrack, null, identity);
        MyTrackInfo myTrackInfo = new MyTrackInfo(userName, userPhone, localVideoTrack, null, identity);
        trackInfoMap.put(userPhone, myTrackInfo);
        playingTrack = myTrackInfo;

//        RTCManager.setRoomEventListener(this);
        mEngine.setEventListener(this);

        mEngine.setAudioSourceCallback(this);

        mEngine.joinRoom(roomToken);

    }


    /**
     * 设置画面质量
     */
    private void setQuality() {

        //是否开启硬编码
        boolean isHwCodec = false;
        //设置是否固定分辨率
        boolean isMaintainRes = false;
        int videoWidth = DEFAULT_RESOLUTION[1][0];
        int videoHeight = DEFAULT_RESOLUTION[1][1];
        int fps = DEFAULT_FPS[1];
        int videoBitrate = DEFAULT_BITRATE[1];

        QNVideoFormat format = new QNVideoFormat(videoWidth, videoHeight, fps);
        setting = new QNRTCSetting();
        setting.setCameraID(QNRTCSetting.CAMERA_FACING_ID.FRONT)//配置默认摄像头 ID
                .setHWCodecEnabled(isHwCodec)//是否开启硬编码
                .setMaintainResolution(isMaintainRes)//设置是否固定分辨率
                .setVideoBitrate(videoBitrate)//毕特率
                .setVideoEncodeFormat(format)//配置视频的编码格式
                .setVideoPreviewFormat(format);//配置预览的编码格式
        showLog("视频清晰度配置:" + videoWidth + "-" + videoHeight + "-" + fps + "-" + videoBitrate);

    }

    private void setTrackQuality(int type) {
        int videoWidth = DEFAULT_RESOLUTION[type][0];
        int videoHeight = DEFAULT_RESOLUTION[type][1];
        int fps = DEFAULT_FPS[type];
        QNVideoFormat format = new QNVideoFormat(videoWidth, videoHeight, fps);

        localVideoTrack = mEngine.createTrackInfoBuilder()
                .setSourceType(QNSourceType.VIDEO_CAMERA)
                .setMaster(true)
                .setVideoPreviewFormat(format)// 配置预览格式
                .setVideoEncodeFormat(format)// 配置编码格式
                .create();

    }


    /**
     * 美颜
     */
    private void initBeauty() {

        /**
         *
         * bl
         * whiten 美白
         * redden 色彩饱和度(红色)
         *
         *
         */
        QNBeautySetting beautySetting = new QNBeautySetting(0.5f, 0.5f, 0.5f);
        beautySetting.setEnable(true);
        mEngine.setBeauty(beautySetting);

    }


    /**
     * 当按下屏幕返回键时，调用退出接口
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            LogUtil.e("点击了返回按钮！");

            if ("1".equals(identity)) {

                showToast("请点击下课按钮完成下课哦！");
            } else {

                showToast("老师还没下课，还不能退出直播间哦！");

            }
            return false;
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onStop() {
        super.onStop();

        //true代表当前正在后台运行，暂不退出直播间
        if (ActivityUtils.isBackground(this)) {

            LogUtil.e("app已经不在后台运行，退出直播间");
            //false代表程序已经被杀死，需要退出直播间
//            requestLeaveRoom();
            clearConfigInfo();

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        clearConfigInfo();

    }

    /**
     * 离开房间
     */
    //老师每次下课扣除1个课时
    private void leaveRoom() {

        CoachAIStudyDialog.getInstance()
                .setContent("确认要退出直播间么？")
                .setCancelText("取消")
                .setSuerText("确定")
                .setSureListener(new CoachAIStudyDialog.SurelListener() {
                    @Override
                    public void onSure() {

                        requestLeaveRoom();

                    }
                }).show(getSupportFragmentManager());

    }

    /**
     * 请求离开房间
     */
    int leaveRequestNum = 0;

    private void requestLeaveRoom() {

        LogUtil.e("请求requestLeaveRoom()接口时，leaveRequestNum的值为：" + leaveRequestNum);

        HttpUtils.with(CoachStudyLivingActivity.this)
                .addParam("requestType", "LIVE_DROPOTU_ROOM")
                .addParam("room_name", roomName)
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .addParam("consume_class", "1")
                .execute(new HttpNormalCallBack<CloseRoomBean>() {
                    @Override
                    public void onSuccess(CloseRoomBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            LogUtil.e("退出直播间成功");

                            //将是否等待数据设置为0，方便外部判断
                            UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(CoachStudyLivingActivity.this).getUserCache();
                            userCacheInterface.setIsWait(0);

                            //更新新版问答老师显示首页
                            ObserverManager.getInstance().notifyObserver("updateNewShareCare");

                            clearConfigInfo();

                        } else {

                            //当返回码不等于200时，再次请求退出接口
                            ++leaveRequestNum;
                            LogUtil.e("请求出错fail时，leaveRequestNum的值为：" + leaveRequestNum);
                            //请求三次依然出现错误时，直接强制退出直播间
                            if (leaveRequestNum <= 3) {
                                requestLeaveRoom();
                            } else if (leaveRequestNum > 3) {
                                clearConfigInfo();
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                        //当请求出现错误时，再次请求退出接口
                        ++leaveRequestNum;
                        LogUtil.e("请求出错onError时，leaveRequestNum的值为：" + leaveRequestNum);
                        //请求三次依然出现错误时，直接强制退出直播间
                        if (leaveRequestNum <= 3) {
                            requestLeaveRoom();
                        } else if (leaveRequestNum > 3) {
                            clearConfigInfo();
                        }
                    }
                });
    }


    public void clearConfigInfo() {
        //清空七牛数据
        if (mEngine != null) {
            mEngine.destroy();
            mEngine = null;
        }

        ObserverManager.getInstance().remove(this);
        if (dialog != null) {
            dialog.dismiss();
        }

        //清空fragment和观察者模式
        removeFragment();

        imSocketUtils.closeSocket();
        trackInfoMap.clear();

        finish();

    }

    private void removeFragment() {
        FragmentCustomUtils.removeFragment(this, FragmentTag.CoachStudyControlFragment);
        FragmentCustomUtils.removeFragment(this, FragmentTag.CoachStudyUserListFragment);
        FragmentCustomUtils.removeFragment(this, FragmentTag.CoachStudyWhiteBroadFragment);
    }

    @Override
    public void onRoomStateChanged(QNRoomState qnRoomState) {

        LogUtil.e("onRoomStateChanged");

        switch (qnRoomState) {
            case RECONNECTING:
                //重新连接中
                showToast("重新连接中");
                break;
            case CONNECTED:
                //连接成功
                toTeacherPublishTrack();
                showLog("连接直播房间成功");

                if (isTeacherPublicVoice == 2) {
                    LogUtil.e("老师重新发布语音哦！");
                    mEngine.startCapture();
                    localAudioTrack.setMuted(false);
                    mEngine.publishTracks(Arrays.asList(localAudioTrack));
                }
                break;
            case RECONNECTED:
                //重新连接成功
                break;
            case CONNECTING:
                //连接中
                showToast("连接中");
                break;
        }

    }

    /**
     * 当退出房间执行完毕后触发该回调，可用于切换房间
     */
//    @Override
//    public void onRoomLeft() {
//
//    }

    /**
     * 学生申请麦克风成功
     */
    public void requestVoiceSuccess() {

        isStudentHaveVoice = true;

        mEngine.publishTracks(Arrays.asList(localAudioTrack));

        MyTrackInfo myTrackInfo = new MyTrackInfo(userName, userPhone, localVideoTrack, localAudioTrack, identity);
//        MyTrackInfo myTrackInfo = new MyTrackInfo(userPhone, localVideoTrack, localAudioTrack, identity);
        trackInfoMap.put(userPhone, myTrackInfo);
        updateVideoFragment();

    }


    /**
     * 更新直播列表
     */
    private void updateVideoFragment() {

        if (studyUserListFragment != null) {
            studyUserListFragment.setStudentTrackInfo(trackInfoMap.getOrderedValues());
        }

//        if (studyUserListFragment != null) {
//            studyUserListFragment.setStudentTrackInfo(studentTrackInfoMap.getOrderedValues());
//            studyUserListFragment.setTeacherTrackInfo(teacherTrackInfoMap.getOrderedValues());
//        }

    }

    /**
     * 推送流
     */
    private void toTeacherPublishTrack() {

        LogUtil.e("连接成功，发布视频流和音频流");

        if (identity.equals("1")) {
            mEngine.publishTracks(Arrays.asList(localVideoTrack, localAudioTrack));
            MyTrackInfo myTrackInfo = new MyTrackInfo(userName, userPhone, localVideoTrack, localAudioTrack, identity);
            trackInfoMap.put(userPhone, myTrackInfo);
            updateVideoFragment();
        } else if (identity.equals("2")) {
            mEngine.publishTracks(Arrays.asList(localVideoTrack, null));
            MyTrackInfo myTrackInfo = new MyTrackInfo(userName, userPhone, localVideoTrack, null, identity);
            trackInfoMap.put(userPhone, myTrackInfo);
            updateVideoFragment();
        }
//        if (identity.equals("1")) {
//            mEngine.publishTracks(Arrays.asList(localVideoTrack, localAudioTrack));
//            MyTrackInfo myTrackInfo = new MyTrackInfo(userPhone, localVideoTrack, localAudioTrack, identity);
//            trackInfoMap.put(userPhone, myTrackInfo);
//            updateVideoFragment();
//        } else if (identity.equals("2")) {
//            mEngine.publishTracks(Arrays.asList(localVideoTrack, null));
//            MyTrackInfo myTrackInfo = new MyTrackInfo(userPhone, localVideoTrack, null, identity);
//            trackInfoMap.put(userPhone, myTrackInfo);
//            updateVideoFragment();
//        }

//        updateVideoFragment();
    }

//    @Override
//    public void onRemoteUserReconnecting(String s) {
//
//        LogUtil.e("远端用户：" + s + "正在连接中...");
//    }
//
//    @Override
//    public void onRemoteUserReconnected(String s) {
//
//        LogUtil.e("远端用户：" + s + "连接成功");
//    }

    @Override
    public void onRemoteUserJoined(String s, String s1) {
        LogUtil.e("直播-onRemoteUserJoined用户加入:" + s + "消息:" + s1);

        if (s.equals(teacherPhone)) {
            MyTrackInfo myTrackInfo = trackInfoMap.get(s);
            if (myTrackInfo == null) {
                myTrackInfo = new MyTrackInfo();
            }
            myTrackInfo.setUserId(s);
            trackInfoMap.put(s, myTrackInfo, s.equals(teacherPhone));
            updateVideoFragment();
        } else {
            getUserNameFromPhone(s);
        }
    }

    //根据手机号查询用户昵称
    public void getUserNameFromPhone(final String s) {

        HttpUtils.with(this)
                .addParam("requestType", "GET_NAME_BASED_ON_PHONE")
                .addParam("user_phone", s)
                .execute(new HttpNormalCallBack<GetUserNameFromPhone>() {
                    @Override
                    public void onSuccess(GetUserNameFromPhone result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (StringUtil.isNotEmpty(result.getObj().getUser_name(), true)) {

                                LogUtil.e("根据电话查出的姓名为：" + result.getObj().getUser_name());

                                MyTrackInfo myTrackInfo = trackInfoMap.get(s);
                                if (myTrackInfo == null) {
                                    myTrackInfo = new MyTrackInfo();
                                }
                                myTrackInfo.setUserId(s);
                                myTrackInfo.setUserName(result.getObj().getUser_name());
                                trackInfoMap.put(s, myTrackInfo, s.equals(teacherPhone));
                                updateVideoFragment();
                            }

                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    @Override
    public void onRemoteUserLeft(String s) {
        LogUtil.e("直播-onRemoteUserLeft用户离开:" + s);
        LogUtil.e("teacherPhone的值为：" + teacherPhone);

        //老师点击下课退出直播间，不处理
        if (isTeacherClose) {

        } else {

            //如果是老师异常退出直播间，提示学生等待
            if (s.equals(teacherPhone)) {
                classState = 1;

                OneButtonDialog.getInstance()
                        .setTitle("温馨提示")
                        .setContent("老师正在重新连接中，请在直播间中等待......")
                        .setSureListener(new OneButtonDialog.SurelListener() {
                            @Override
                            public void onSure() {

                            }
                        })
                        .show(getSupportFragmentManager());

            }
        }

        trackInfoMap.remove(s);

        //访问接口，判断该账号身份
//        boolean isteacher = false;
//
//        if (isteacher) {
//
//            teacherTrackInfoMap.remove(s);
//        } else {
//
//            studentTrackInfoMap.remove(s);
//        }

        updateVideoFragment();

    }


    @Override
    public void onLocalPublished(List<QNTrackInfo> list) {
        LogUtil.e("直播-onLocalPublished数据大小:" + list.size());
    }

    private void logQNTrackInfo(List<QNTrackInfo> list) {

        for (QNTrackInfo qnTrackInfo : list) {
            LogUtil.e(qnTrackInfo.toString());
        }

    }

    @Override
    public void onRemotePublished(String remoteUserId, List<QNTrackInfo> list) {

        LogUtil.e("直播-onRemotePublished数据大小:" + list.size());
        logQNTrackInfo(list);

        MyTrackInfo myTrackInfo = null;

        for (QNTrackInfo track : list) {

            myTrackInfo = trackInfoMap.get(track.getUserId());
            if (myTrackInfo == null) {
                myTrackInfo = new MyTrackInfo();
            }
            myTrackInfo.setUserId(track.getUserId());
            if (track.getTrackKind().equals(QNTrackKind.VIDEO)) {
                myTrackInfo.setVideoTrack(track);

            } else {
                myTrackInfo.setAudioTrack(track);
            }

        }

        //访问接口，判断该账号身份
//        boolean isteacher = false;
//
//        if (isteacher) {
//
//            teacherTrackInfoMap.put(myTrackInfo.getUserId(), myTrackInfo);
//        } else {
//
//            studentTrackInfoMap.put(myTrackInfo.getUserId(), myTrackInfo);
//        }

        trackInfoMap.put(myTrackInfo.getUserId(), myTrackInfo, myTrackInfo.getUserId().equals(teacherPhone));

        updateVideoFragment();

    }

    @Override
    public void onRemoteUnpublished(String remoteUserId, List<QNTrackInfo> list) {
        LogUtil.e("直播-onRemoteUnpublished数据大小:" + list.size());
        //logQNTrackInfo(list);

        for (QNTrackInfo track : list) {
            if (null == trackInfoMap.get(track.getUserId())) {
                LogUtil.e("获取到远程取消订阅回调，获取不到用户的Id");
            } else {
                if (track.getTrackKind().equals(QNTrackKind.VIDEO)) {
                    trackInfoMap.get(track.getUserId()).setVideoTrack(null);
                } else {
                    trackInfoMap.get(track.getUserId()).setAudioTrack(null);
                }
            }
        }
        updateVideoFragment();

    }

    @Override//当远端用户进行了关闭语音/摄像头之后会触发的回调
    public void onRemoteUserMuted(String remoteUserId, List<QNTrackInfo> list) {
        LogUtil.e("直播-onRemoteUserMuted人数:" + list.size());

        //通过用户ID获取到该用户的数据
        MyTrackInfo trackInfo = trackInfoMap.get(remoteUserId);

        for (int i = 0; i < list.size(); i++) {
            LogUtil.e(list.get(i).getTrackKind().toString());
            //获取并判断用户关闭的类型
            if ("VIDEO".equals(list.get(i).getTrackKind().toString())) {
                trackInfo.setVideoTrack(null);
            } else if ("AUDIO".equals(list.get(i).getTrackKind().toString())) {
                trackInfo.setAudioTrack(null);
            }
        }

        //访问接口，判断该账号身份
//        boolean isteacher = false;
//
//        if (isteacher) {
//
//            teacherTrackInfoMap.put(remoteUserId, trackInfo);
//        } else {
//
//            studentTrackInfoMap.put(remoteUserId, trackInfo);
//        }

        trackInfoMap.put(remoteUserId, trackInfo, remoteUserId.equals(teacherPhone));
        updateVideoFragment();

    }

    @Override
    public void onSubscribed(String remoteUserId, List<QNTrackInfo> list) {
        LogUtil.e("直播-onSubscribed人数:" + list.size());

    }

//    @Override
//    public void onSubscribedProfileChanged(String s, List<QNTrackInfo> list) {
//
//    }

    @Override
    public void onKickedOut(String s) {

        LogUtil.e("onKickedOut中被踢出的人的账号为：" + s);

        //如果异常退出，则将用户暂时踢出房间
//        if (mEngine == null) {
//            mEngine = QNRTCEngine.createEngine(getApplicationContext(), setting, CoachStudyLivingActivity.this);
//        }
//
//        mEngine.kickOutUser(s);

    }

    @Override
    public void onStatisticsUpdated(QNStatisticsReport qnStatisticsReport) {
        LogUtil.e("直播-onStatisticsUpdated");
    }

//    @Override
//    public void onRemoteStatisticsUpdated(List<QNStatisticsReport> list) {
//
//    }


    @Override
    public void onAudioRouteChanged(QNAudioDevice qnAudioDevice) {

        int str = qnAudioDevice.value();
        LogUtil.e("直播-onAudioRouteChanged中类型为：" + str);

        LogUtil.e("直播-onAudioRouteChanged");
    }

    @Override
    public void onCreateMergeJobSuccess(String s) {
        LogUtil.e("直播-onCreateMergeJobSuccess");
    }

//    @Override
//    public void onCreateForwardJobSuccess(String s) {
//
//    }

    @Override
    public void onError(int errorCode, String description) {
        LogUtil.e("onError");

        if (errorCode == QNErrorCode.ERROR_TOKEN_INVALID
                || errorCode == QNErrorCode.ERROR_TOKEN_ERROR
                || errorCode == QNErrorCode.ERROR_TOKEN_EXPIRED) {
            showToast("roomToken 错误，请重新加入房间");
        } else if (errorCode == QNErrorCode.ERROR_AUTH_FAIL
                || errorCode == QNErrorCode.ERROR_RECONNECT_TOKEN_ERROR) {

            showToast("roomToken 错误");

        } else if (errorCode == QNErrorCode.ERROR_PUBLISH_FAIL) {

            showToast("发布失败，请重新加入房间发布");
        } else {
            showToast("errorCode:" + errorCode + " description:" + description);
        }
    }

//    @Override
//    public void onMessageReceived(QNCustomMessage qnCustomMessage) {
//
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PhotoUtil.CoachStudy_StudentUploadFinishedWork:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> boardSelectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia boardMedia = boardSelectList.get(0);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    if (boardMedia.isCompressed()) {
                        String compressPath = boardMedia.getCompressPath();
                        if (studyControlFragment != null) {
                            studyControlFragment.upLoadImage(compressPath);
                        }
                    }
                    break;
            }

        } else if (resultCode == RESULT_CANCELED) {

            LogUtil.e("学生取消上传家庭作业");

            if (mEngine == null) {
                mEngine = QNRTCEngine.createEngine(getApplicationContext(), setting, CoachStudyLivingActivity.this);
            }

            mEngine.startCapture();
            if (isStudentHaveVoice) {
                mEngine.publishTracks(Arrays.asList(localVideoTrack, localAudioTrack));
            } else {
                mEngine.publishTracks(Arrays.asList(localVideoTrack, null));
            }
            LogUtil.e("学生取消上传家庭作业，摄像头采集开始采集");
        }
    }

    private WhiteBroadView whiteBroadView;
    WhiteBoardUtils whiteBoardUtils;

    private static Room whiteBoardRoom;

    /**
     * 初始化白板状态
     */
    private void initWhiteBoradStae() {

        //显示白板
        frWhiteBroad.setVisibility(View.GONE);

        if (whiteBoardRoom != null) {
            //开启白板操作权限
            whiteBoardRoom.disableDeviceInputs(false);
            if ("1".equals(identity)) {
                whiteBoardRoom.setViewMode(ViewMode.Broadcaster);
            } else if ("2".equals(identity)) {
                whiteBoardRoom.setViewMode(ViewMode.Follower);
            }
            //设置白板摄像头固定，无法缩放图片
            whiteBoardRoom.disableCameraTransform(true);
            //设置白板图铺满屏幕
            whiteBoardRoom.scalePptToFit(AnimationMode.Continuous);
            studyWhiteBroadFragment.refreshRoom();
        }

    }


    /**
     * 初始化白板
     */
    private void initWhiteBorad() {

        whiteBroadView = new WhiteBroadView(this);
        whiteBoardUtils = WhiteBoardUtils.getInstance().joinToRoom(
                this, whiteBroadView, uuid, whitetoken, userPhone);

        whiteBoardUtils.setWhiteBoardListener(new WhiteBoardUtils.WhiteBoardListener() {
            @Override
            public void onJoinRoomSucess(Room room) {
                if (studyWhiteBroadFragment != null) {
                    whiteBoardRoom = room;
                    studyWhiteBroadFragment.setRoom(room);

                    //初始化画笔颜色
//                    studyWhiteBroadFragment.setBoradTool(Appliance.PENCIL);
//                    whiteBoardRoom.disableEraseImage(true);

                    showLog("room回调");

                    //初始化白板状态
                    initWhiteBoradStae();

                    //添加白板监听事件
                    addEvevtListener();

                }
            }

            @Override//当房间状态改变时，刷新白板和用户列表
            public void onRoomStateChange() {

            }

            @Override//尝试重新加入房间
            public void onRetryJoinin() {

                if (whiteBroadView == null) {
                    whiteBroadView = new WhiteBroadView(CoachStudyLivingActivity.this);
                }
                whiteBoardUtils = WhiteBoardUtils.getInstance().joinToRoom(CoachStudyLivingActivity.this,
                        whiteBroadView, uuid, whitetoken, userPhone);

            }

            @Override//当老师下课之后，主动让学生退出直播间
            public void onKickedOutRoom(String reason) {

                LogUtil.e("onKickedOut" + reason);

                //接收到老师下课通知
                isTeacherClose = true;

                //老师点击了下课并且当前为学生，则提示退出直播间
                if (isTeacherClose && "2".equals(identity)) {

                    LogUtil.e("============老师下课啦");
                    OneButtonDialog.getInstance()
                            .setTitle("温馨提示")
                            .setContent("本次课程已结束，请退出直播间")
                            .setSureListener(new OneButtonDialog.SurelListener() {
                                @Override
                                public void onSure() {

                                    //发送连线时长信息到服务器
//                                    sendConnectTimeToService();

                                    requestLeaveRoom();
                                }
                            }).show(getSupportFragmentManager());

                }
            }
        });
    }


    public static final String EVENT_NAME = "WHITEBROADCOMMANDCOACHSTUDYMESSAGE";

    /**
     * 添加自定义事件，用于获取用户列表以及显示聊天消息
     */
    private void addEvevtListener() {

        whiteBoardRoom.addMagixEventListener(EVENT_NAME, new EventListener() {
            @Override
            public void onEvent(EventEntry eventEntry) {
                if (eventEntry != null) {
                    if (EVENT_NAME.equals(eventEntry.getEventName())) {
                        String json = null;
                        //因为白板SDK问题，eventEntry.getPayload()可能会出现String或者Object，分别判断一下
                        if (eventEntry.getPayload() instanceof String) {
                            LogUtil.e("eventEntry.getPayload()类型为String");
                            json = (String) eventEntry.getPayload();
                        } else if (eventEntry.getPayload() instanceof Object) {
                            LogUtil.e("eventEntry.getPayload()类型为Object");
                            json = MGson.newGson().toJson(eventEntry.getPayload());
                        }
                        LogUtil.e("白板自定义收到的json为：" + json);
                        RoomChatBean chatBean = MGson.newGson().fromJson(json, RoomChatBean.class);
                        //辅导作业直播间事件类型区分
                        /*
                         * 1.学生提交了作业，提醒老师查看作业
                         * 2.老师批改了作业，提醒学生在作业记录中查看
                         * 3.学生举手，提醒老师查看举手列表
                         * 4.老师，同意、拒绝举手申请，返回给学生
                         * 5.学生申请下课，老师处理
                         * 6.老师处理申请下课结果返回给学生
                         * */
                        if ("1".equals(chatBean.getType())) {
                            if ("1".equals(identity)) {

                                showStudentOperateDialog(chatBean.getUserName(), "已提交作业",
                                        "查看作业列表");
                            }
                        } else if ("3".equals(chatBean.getType())) {
                            if ("1".equals(identity)) {

                                showStudentOperateDialog(chatBean.getUserName(), "举手了",
                                        "申请列表");

                            }
                        } else if ("5".equals(chatBean.getType())) {
                            if ("1".equals(identity)) {

                                showStudentOperateDialog(chatBean.getUserName(), "申请下课",
                                        "申请下课列表");
                            }
                        } else if ("6".equals(chatBean.getType())) {//通知老师学生进入直播间
                            if ("2".equals(identity)) {

//                                LogUtil.e("============老师下课啦");
//                                OneButtonDialog.getInstance()
//                                        .setTitle("温馨提示")
//                                        .setContent("本次课程已结束，请退出直播间")
//                                        .setSureListener(new OneButtonDialog.SurelListener() {
//                                            @Override
//                                            public void onSure() {
//                                                requestLeaveRoom();
//                                            }
//                                        }).show(getSupportFragmentManager());
                            }
                        }
                    }
                }
            }
        });
    }


    /**
     * 弹出工具框
     *
     * @param studentName 申请的学员姓名
     * @param operateType 申请的类型  -- 举手，提交作业等
     * @param operateList 需要去处理的列表  -- 举手列表，作业列表等
     */
    public void showStudentOperateDialog(String studentName, String operateType, String operateList) {

        if (StringUtil.isNotEmpty(studentName, true) &&
                StringUtil.isNotEmpty(operateType, true) &&
                StringUtil.isNotEmpty(operateList, true)) {

            CoachAIStudyDialog.getInstance()
                    .setTitle("温馨提示")
                    .setContent("学生" + studentName + operateType + "，请在" + operateList + "中处理！")
                    .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                        @Override
                        public void onCancel() {

                        }
                    })
                    .setSureListener(new CoachAIStudyDialog.SurelListener() {
                        @Override
                        public void onSure() {

                        }
                    }).show(getSupportFragmentManager());

        }
    }


    public StudyControlMenuFragment.StudyControlMenuFragmentListener controlFragmentListener = new StudyControlMenuFragment.StudyControlMenuFragmentListener() {

        @Override
        public void onSetHomeWorkTime() {//设置作业的内容以及时间

        }

        @Override
        public void onSeeFinishedWork() {//查看学生提交的作业

        }

        @Override
        public void onApplyList() {//查看举手列表

        }

        @Override
        public void onSeeRecordList() {//查看作业历史记录

//            showRecordDialogFragment();
        }

        @Override
        public void onTeacherCloseRoom() {//老师下课

            //如果是老师点击了下课按钮，就需要进行赋值，方便后面判断
            if ("1".equals(identity)) {
                isTeacherClose = true;
            }
            leaveRoom();

            //发送本次连线数据到后台
//            sendConnectTimeToService();
        }

        @Override
        public void onStudentSwitchCamera() {

            mEngine.switchCamera(new QNCameraSwitchResultCallback() {
                @Override
                public void onCameraSwitchDone(boolean b) {

                    //true为前置摄像头，false为后置摄像头
                    LogUtil.e("切换摄像头========================>" + b);

                }

                @Override
                public void onCameraSwitchError(String s) {

                    LogUtil.e("切换摄像头失败，原因是：========================>" + s);
                }
            });

        }

        @Override
        public void onStudentWorkList() {//查看作业安排列表

        }

        @Override
        public void onStudentUploadWork() {//学生上传作业

        }

        @Override
        public void onStudentApply() {//学生举手

            //向后台提交举手数据，并发送白板事件
            sengWhiteEventMsg("3", "");
            showToast("已向老师申请语音，等待老师回复哦！");

        }

        @Override
        public void onStudentSeeRecord() {//学生查看作业记录

//            showRecordDialogFragment();
        }

        @Override
        public void onUploadImgSuccess() {

            //向后台提交上传作业成功数据，并发送白板事件
            sengWhiteEventMsg("1", "");
            showToast("作业提交成功，等待老师批改哦！");
        }

        @Override
        public void onAllowVoice(String userPhone) {

            //学生申请语音成功
            requestVoiceSuccess();
        }

        @Override
        public void onRefuseVoice(String userPhone) {

        }

        @Override
        public void onStudentTakePhoto(int type) {

            if (mEngine == null) {
                mEngine = QNRTCEngine.createEngine(getApplicationContext(), setting, CoachStudyLivingActivity.this);
            }

            //0代表需要暂时关闭摄像头采集
            if (0 == type) {

                mEngine.stopCapture();
                mEngine.unPublish();
                LogUtil.e("摄像头采集暂时停止");

                PhotoUtil.normalSelectPictureByCode(CoachStudyLivingActivity.this, listImage,
                        1, PhotoUtil.CoachStudy_StudentUploadFinishedWork);
            } else if (1 == type) {

                mEngine.startCapture();
                if (isStudentHaveVoice) {
                    mEngine.publishTracks(Arrays.asList(localVideoTrack, localAudioTrack));
                } else {
                    mEngine.publishTracks(Arrays.asList(localVideoTrack, null));
                }
                LogUtil.e("摄像头采集开始采集");
            }

        }

        @Override
        public void onTeacherAddRecord(int type) {

            if (mEngine == null) {
                mEngine = QNRTCEngine.createEngine(getApplicationContext(), setting, CoachStudyLivingActivity.this);
            }

            //0代表需要暂时不在直播间发布语音
            if (0 == type) {

//                mEngine.stopCapture();
//                mEngine.unPublishAudio();

                mEngine.stopCapture();
                localAudioTrack.setMuted(true);
                mEngine.unPublishTracks(Arrays.asList(localAudioTrack));
                LogUtil.e("老师暂时不发布语音");


            } else if (1 == type) {

                LogUtil.e("直播间当前状态为：" + mEngine.getRoomState());
                if (mEngine.getRoomState() == QNRoomState.CONNECTED) {

//                    mEngine.startCapture();
//                    mEngine.publishAudio();

                    mEngine.startCapture();
                    localAudioTrack.setMuted(false);
                    mEngine.publishTracks(Arrays.asList(localAudioTrack));

                    isTeacherPublicVoice = 1;
//                    mEngine.publishTracks(Arrays.asList(localVideoTrack, localAudioTrack));

                    LogUtil.e("老师重新开始发布语音");
                } else {

                    isTeacherPublicVoice = 2;
                    showToast("正在重连中，请稍等...");
                }
            }

        }
    };


    //用于判断老师发布语音是否成功   0---初始值  1---再次发布成功   2----再次发布失败
    public int isTeacherPublicVoice = 0;

    //用于判断学生是否可以发布语音
    public boolean isStudentHaveVoice = false;


    List<LocalMedia> listImage = new ArrayList<>();

    /**
     * 通过白板自定义事件发送消息
     *
     * @param type
     * @param message
     */
    public void sengWhiteEventMsg(String type, String message) {
        RoomChatBean chatBean = new RoomChatBean();
        chatBean.setMessageId(TimeUtils.getNowTimestamp() + "");
        chatBean.setMessage(message);
        chatBean.setType(type);
        chatBean.setUserIcon(userIcon);
        chatBean.setUserName(userName);
        chatBean.setIdentity(identity);

        String json = MGson.newGson().toJson(chatBean);
        AkkoEvent akkoEvent = new AkkoEvent(EVENT_NAME, json);
        LogUtil.e("用户发送的数据为：" + json);

        if (whiteBoardRoom != null) {
            whiteBoardRoom.dispatchMagixEvent(akkoEvent);
        }
    }

    public StudyUserListFragment.StudyUserListFragmentListener userListFragmentListener = new StudyUserListFragment.StudyUserListFragmentListener() {

        @Override
        public void onFindAdmin(MyTrackInfo trackInfo) {

            if (mEngine == null) {
                mEngine = QNRTCEngine.createEngine(getApplicationContext(), setting, CoachStudyLivingActivity.this);
            }
            mEngine.setRenderWindow(trackInfo.getVideoTrack(), localSurfaceView);
        }

        @Override
        public void onSetQNSurfaceView(MyTrackInfo trackInfo, QNSurfaceView qnSurfaceView) {

//            studentSurfaceView.setVisibility(View.GONE);
//            frUserList.setVisibility(View.VISIBLE);
            mEngine.setRenderWindow(trackInfo.getVideoTrack(), qnSurfaceView);
        }
    };


    private void sendConnectTimeToService() {

        String time = tvTime.getText().toString().trim();
        LogUtil.e("直播时长time的值为：" + time);
        if (StringUtil.isNotEmpty(time, true)) {
            HttpUtils.with(this)
                    .addParam("requestType", "LIVE_BROADCAST_DEDUCTION_AMOUNT")
                    .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                    .addParam("live_time", time)//直播时长
                    .addParam("course_id", course_id)
                    .addParam("is_normal", classState)
                    .execute(new HttpNormalCallBack<DaYiConectTimeRecordBean>() {
                        @Override
                        public void onSuccess(DaYiConectTimeRecordBean result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {
                                LogUtil.e("直播时长修改成功");

                                requestLeaveRoom();
                            }
                        }

                        @Override
                        public void onError(String e) {

                        }
                    });
        }
    }

    @Override
    public void onAudioSourceAvailable(ByteBuffer srcBuffer, int size, long tsInNanoTime) {

        /**
         * @param srcBuffer 音频 buffer
         * @param size 音频 buffer 大小
         * @param tsInNanoTime 音频时间戳，单位 ns
         */
//        LogUtil.e("语音流的ByteBuffer为：" + srcBuffer.toString() + "，音频大小为："
//                + size + "，音频时间戳为：" + tsInNanoTime);

    }

    @Override
    public void observerUpData(String content) {

        if (StringUtil.isNotEmpty(content, true)) {

            LogUtil.e("收到消息，马上关闭抽奖框！");
            if ("closeLuckyDraw".equals(content)) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        }
    }
}
